import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'
import router from "@/router";
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
// 传2个回调，成功执行config回调，失败执行error回调
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const {data, message, success} = response.data
    if (success) {
      return data
    } else {
      Message({
        message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message))
    }
  },
  async error => {
    if (error.response.status === 401) {
      Message({ type: 'warning', message: 'token超时了' })
      // token失效，退出登录，清空token，清空用户信息，跳转到登录
      // 加上await是要等到用户信息和token都删干净了再跳转
      await store.dispatch('user/loginOut') // 调用action 退出登录
      router.push('/login')
      return Promise.reject(error)
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
